package work.darren.itext7.generator;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.font.FontInfo;
import com.itextpdf.layout.font.FontProvider;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import work.darren.itext.common.api.PdfGenerator;
import work.darren.itext.common.util.IOUtils;
import work.darren.itext7.event.PageMarker;
import work.darren.itext7.event.WaterMarker;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Itext7 实现HTML转PDF
 *
 * @author darren
 * @date 2019-05-25
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Itext7Generator implements PdfGenerator {

    private FontProvider fontProvider;

    private static Itext7Generator instanse;

    public static PdfGenerator getInstanse() {
        if (instanse == null) {
            synchronized (Itext7Generator.class) {
                if (instanse == null) {
                    instanse = new Itext7Generator();
                    instanse.initFont();
                }
            }
        }

        return instanse;
    }

    private void initFont() {
        try (InputStream inputStream = PdfGenerator.class.getResourceAsStream(fontpath())) {
            fontProvider = new FontProvider();
            fontProvider.addFont(IOUtils.toByteArray(inputStream));
        } catch (IOException e) {
            throw new RuntimeException("中文字体初始化失败", e);
        }
    }

    @Override
    public void generatePdf(String html, String outputFile) throws Exception {
        PdfWriter   writer = new PdfWriter(new FileOutputStream(outputFile));
        PdfDocument doc    = new PdfDocument(writer);
        doc.setDefaultPageSize(PageSize.A4);
        doc.getDefaultPageSize().applyMargins(20, 20, 20, 20, true);

        FontInfo cnFont = fontProvider.getFontSet()
                .getFonts()
                .stream()
                .findFirst()
                .orElse(null);
        PdfFont pdfFont = fontProvider.getPdfFont(cnFont);

        doc.addEventHandler(PdfDocumentEvent.END_PAGE, new WaterMarker(pdfFont));

        doc.addEventHandler(PdfDocumentEvent.END_PAGE, new PageMarker(pdfFont));

        ConverterProperties properties = new ConverterProperties();
        properties.setFontProvider(fontProvider);

        HtmlConverter.convertToPdf(html, doc, properties);
    }
}
